package org.hepeng.commons.spring.cloud.netflix.eureka;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hepeng.commons.spring.context.ApplicationContextHolder;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.eureka.CloudEurekaInstanceConfig;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import java.util.List;
import java.util.Objects;

/**
 * @author he peng
 */
public class EurekaDiscoveryClientUtils {

    private static DiscoveryClient DISCOVERY_CLIENT;

    static {
        init();
    }

    private static void init() {
        DISCOVERY_CLIENT = ApplicationContextHolder.getApplicationContext().getBean(DiscoveryClient.class);
    }


    public static String getServiceInstanceId() {
        CloudEurekaInstanceConfig cloudEurekaInstanceConfig =
                ApplicationContextHolder.getApplicationContext()
                        .getBean(CloudEurekaInstanceConfig.class);
        return cloudEurekaInstanceConfig.getInstanceId();
    }

    public static EurekaDiscoveryClient.EurekaServiceInstance getServiceInstance() {
        ApplicationContext applicationContext = ApplicationContextHolder.getApplicationContext();
        Environment environment = applicationContext.getEnvironment();
        String applicationName = environment.getProperty("spring.application.name");
        String instanceId = getServiceInstanceId();
        List<ServiceInstance> instances = DISCOVERY_CLIENT.getInstances(applicationName);

        EurekaDiscoveryClient.EurekaServiceInstance serviceInstance = null;
        if (CollectionUtils.isNotEmpty(instances)) {
            for (ServiceInstance instance : instances) {
                if (! EurekaDiscoveryClient.EurekaServiceInstance.class.isAssignableFrom(instance.getClass())) {
                    continue;
                }
                EurekaDiscoveryClient.EurekaServiceInstance eurekaServiceInstance = (EurekaDiscoveryClient.EurekaServiceInstance) instance;
                if (StringUtils.equals(eurekaServiceInstance.getInstanceInfo().getInstanceId() , instanceId)) {
                    serviceInstance = eurekaServiceInstance;
                    break;
                }
            }
        }
        return serviceInstance;
    }

}
